/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.startup.musicstore.services.Impl;

import com.startup.musicstore.app.facade.Facade;
import com.startup.musicstore.model.CreditCard;
import com.startup.musicstore.model.Customer;
import com.startup.musicstore.model.CustomerInvoice;
import com.startup.musicstore.model.Orders;
import com.startup.musicstore.services.CustomerInvoiceService;
import com.startup.musicstore.services.crud.CustomerInvoiceCrudService;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author aljay19
 */
@Service("customerInvoiceService")
@Transactional
public class CustomerInvoiceServiceImpl implements CustomerInvoiceService {
    
    private Facade data = new Facade();

    @Override
    public String getCreditCardPayment(Long customerInvoiceID, Long creditCardID) {
        
        CustomerInvoiceCrudService customerInvoiceCrudService = data.getCustomerInvoiceCrudService();
        List<CustomerInvoice> customerInvoices = customerInvoiceCrudService.findAll();
        for (CustomerInvoice ci : customerInvoices) {
            if (customerInvoiceID.equals(ci.getId())) {
                Orders order = ci.getOrder();
                Customer customer = order.getCustomer();
                List<CreditCard> creditCard = customer.getCreditCards();
                for (CreditCard cc : creditCard) {
                    if (creditCardID.equals(cc.getId())) {
                        if (cc.getExpiryDate().after(new Date()) && Double.parseDouble(cc.getBalance().toString()) > Double.parseDouble(ci.getOrderAmount().toString())) {
                            ci.setInvoiceStatus("paid");
                            customerInvoiceCrudService.merge(ci);
                            return "paid";
                        }
                    }
                }
            }
        }
        return "unpaid";
    }
}
